package com.baiyinet.util.webview;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;

import com.baiyinet.BuildConfig;
import com.baiyinet.Constants;
import com.baiyinet.Constants.PATH;
import com.baiyinet.Constants.URL;
import com.baiyinet.biz.PageStatus;
import com.baiyinet.ui.ToolbarOwner;
import com.baiyinet.ui.main.MainActivity_;
import com.baiyinet.util.CookieHelper;
import com.baiyinet.util.IntentUtils;
import com.github.ybq.android.spinkit.SpinKitView;

import org.parceler.Parcels;

import java.util.Map;
import java.util.WeakHashMap;

import myandroid.library.util.ApplicationHelper;

/**
 * 在应用中加载页面
 * @author J.Huang
 * @version 1.0
 * @since 16/12/13
 */
class LoginWebViewClient extends BaseWebViewClient {

    private Activity mActivity;
    private WebView mWebView;
    private SpinKitView mLoadingIndicator;
    private String mToolbarBgColor;

    private ToolbarOwner.IToolbar mToolbar;

    LoginWebViewClient(Activity activity,
                       ToolbarOwner.IToolbar toolbar,
                       String loadUrl,
                       WebView webView,
                       SpinKitView loadingIndicator,
                       String toolbarBgColor) {
        super(loadUrl);
        mActivity = activity;
        mToolbar = toolbar;
        mWebView = webView;
        mLoadingIndicator = loadingIndicator;
        mToolbarBgColor = toolbarBgColor;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        mLoadingIndicator.setVisibility(View.VISIBLE);
//        mWebView.setVisibility(View.INVISIBLE);

        try {
            Uri uri = Uri.parse(url);
            String pageTitle = uri.getQueryParameter("PageTitle");
            mToolbar.setToolbarTitle(pageTitle);
        } catch (UnsupportedOperationException e) {
        }

        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url == null || TextUtils.isEmpty(url)) {
            return true;
        }

        // 下拉刷新
        if (url.equals(mWebView.getUrl())) {
            SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);

            CookieHelper.setWebViewRequestUrlCookie(mActivity, url, sharedPref.getString(Constants.KEY_COOKIE, ""));

            Map<String, String> cookies = new WeakHashMap<>();
            cookies.put("AppOS", "Android");

            view.clearView();
            view.loadUrl(url, cookies);
            return true;
        }

        url = url.toLowerCase().trim();

        Uri uri = Uri.parse(url);
        String path = uri.getPath();
        String pageNav = uri.getQueryParameter("pagenav");

        if (PATH.MAIN.equals(path) || "root".equalsIgnoreCase(pageNav)) {
            // 获取当前URL的CookieInfo保存到本地数据库
            String cookie = CookieHelper.getWebViewRequestUrlCookie(mActivity, url);

            if (!cookie.isEmpty()) {
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString(Constants.KEY_COOKIE, cookie);
                editor.apply();

                toMainPage();
                return true;
            }
        }

        // 同步Cookie
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(mActivity);
        String cookie = sharedPref.getString(Constants.KEY_COOKIE, "");
        CookieHelper.setWebViewRequestUrlCookie(mActivity, url, cookie);

        // TODO: server returns wrong "farword", should be "forward"
        if (pageNav != null && "farword".equals(pageNav.toLowerCase())) {
            PageStatus pageStatus = new PageStatus(url, true, true, mToolbarBgColor);
            IntentUtils.toNewGeneralActivity(mActivity, pageStatus);
            return true;
        }

        view.clearView();
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        mLoadingIndicator.setVisibility(View.GONE);
//        mWebView.setVisibility(View.VISIBLE);
    }

    private void toMainPage() {
//        Intent intent = new Intent();
//        intent.setClass(mActivity, MainActivity_.class);
//        PageStatus pageStatus = new PageStatus(PATH.MAIN, false);
//        intent.putExtra(PageStatus.EXTRA_NAME, Parcels.wrap(pageStatus));
//        mActivity.startActivity(intent);
//        ApplicationHelper.getInstance().removeActivity(mActivity);
//
        IntentUtils.toMain(mActivity, "");
    }
}
